#!/bin/sh

. /etc/utils.sh

bin=$(basename "$0")
usage() {
  echo "$bin [ true | false ]" >&2
  exit 1
}

status() {
  if runnable mocap; then
    out=$(mocap get --trace 2>/dev/null)
    if contains "$out" "0x0" ; then
      echo false
    else
      echo true
    fi
  elif runnable mocactl; then
    if [ -e /tmp/mocatrace.on ]; then
      echo true
    else
      echo false
    fi
  else
    echo error
  fi
}


if [ $# -eq 0 ]; then
  cmd=show
else
  cmd="$1"
fi


case "$cmd" in
  show)
    status
    ;;
  on|true)
    if [ "$(status)" != "true" ]; then
      if runnable mocap; then
        mocap set --trace 1 --restart
      elif runnable mocactl; then
        echo :>/tmp/mocatrace.on
        mocactl trace --dbg
      fi
    fi
    ;;
  off|false)
    if [ "$(status)" != "false" ]; then
      if runnable mocap; then
        mocap set --trace 0 --restart
      elif runnable mocactl; then
        rm -f /tmp/mocatrace.on
        mocactl trace --none
      fi
    fi
    ;;
  *)
    usage
    ;;
esac

if [ "$(status)" = "error" ]; then
  exit 1
fi
